package cn.wen.eeayjoke.presenter.observer;

import android.app.Activity;
import android.widget.Toast;

import java.net.ConnectException;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;

import cn.wen.base.view.banner.DefActivityLifecycleCallbacks;
import cn.wen.core.log.LogUtils;
import cn.wen.base.util.AppConfig;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import retrofit2.adapter.rxjava2.HttpException;

/**
 * 快速处理的回调类
 */

public abstract class QuickObserver<T> implements Observer<T> {
    private Disposable mDisposable;
    private Activity mActivity;
    private DefActivityLifecycleCallbacks mCallbacks;

    public QuickObserver(Activity activity) {
        mActivity = activity;
        mCallbacks = new DefActivityLifecycleCallbacks() {
            @Override
            public void onActivityPaused(Activity activity) {
                unregister();
            }
        };
    }

    public void unregister() {
        cancel();
        if (mActivity != null) {
            mActivity.getApplication().unregisterActivityLifecycleCallbacks(mCallbacks);
        }
        mActivity = null;
        mCallbacks = null;
        mDisposable = null;
    }

    /**
     * 取消
     */
    public void cancel() {
        if (mDisposable != null && !mDisposable.isDisposed()) {
            mDisposable.dispose();
        }
    }

    @Override
    public void onSubscribe(Disposable d) {
        mDisposable = d;
        if (mActivity != null) {
            mActivity.getApplication().registerActivityLifecycleCallbacks(mCallbacks);
        }
        onStart();
    }

    public void onStart() {

    }

    @Override
    public final void onNext(T data) {
        onResponse(data);
        onComplete();
    }

    public abstract void onResponse(T data);

    @Override
    public void onError(Throwable e) {
        e.printStackTrace();
        if (e instanceof SocketTimeoutException || e instanceof ConnectException
                || e instanceof UnknownHostException || e instanceof HttpException) {
            Toast.makeText(AppConfig.getInstance().getContext(), "网络异常，请检查网络", Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(AppConfig.getInstance().getContext(), "" + e.getMessage(), Toast.LENGTH_SHORT).show();
        }
        LogUtils.e("onError-->" + e.getMessage());
        onComplete();
    }

    @Override
    public void onComplete() {

    }


}
